package com.manus;

import com.accurev.common.data.StreamData;
import com.accurev.common.process.AccuWorkProcess;
import com.accurev.common.process.SecurityProcess;
import com.accurev.common.process.StreamProcess;

import java.util.List;

public class AccurevClientImpl implements AccurevClient {

    private SecurityProcess securityProcess;
    private StreamProcess streamProcess;
    private AccuWorkProcess accuWorkProcess;
    private String userName;
    private String userPassword;

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public AccurevClientImpl(String userName, String userPassword) {
        this.userName = userName;
        this.userPassword = userPassword;
    }

    public void setSecurityProcess(SecurityProcess securityProcess) {
        this.securityProcess = securityProcess;
    }

    public void setStreamProcess(StreamProcess streamProcess) {
        this.streamProcess = streamProcess;
    }

    public void setAccuWorkProcess(AccuWorkProcess accuWorkProcess) {
        this.accuWorkProcess = accuWorkProcess;
    }

    @Override
    public int login() {
        return securityProcess.login(userName, userPassword);
    }

    @Override
    public boolean isValidStream(String streamName) {
        boolean validStream = false;
        StreamData streamData = getStreamData(streamName);
        if (streamData != null) {
            validStream = true;
        }
        return validStream;
    }

    private StreamData getStreamData(String streamName) {
        if (streamProcess == null) {
            streamProcess = new StreamProcess();
        }
        return streamProcess.getStreamDetails(streamName);
    }

    @Override
    public List<String> getStreamIssues(String depot, String stream) {
        if (accuWorkProcess == null){
            accuWorkProcess = new AccuWorkProcess();
        }
        List<String> streamIssues = accuWorkProcess.getStreamIssues(depot, userName, stream,
                true, false, false);

        return streamIssues;
    }

    @Override
    public void promoteIssues(String stream) {
        if (accuWorkProcess == null) {
            accuWorkProcess = new AccuWorkProcess();
        }

        accuWorkProcess.promoteIssues(stream, getBasisStream(stream), "/tmp", "/tmp");
    }

    private String getBasisStream(String stream) {
        String basisStream = null;
        StreamData streamData = getStreamData(stream);

        if (streamData != null) {
            basisStream = streamData.getBasisName();
        }
        return basisStream;
    }
}
